const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
const PGutils =  require("./pgUtils");
const pgUtils = require('./pgUtils');


app.use(express.static("saas"));
app.use(express.static("js"));
// Middleware to parse JSON bodies
app.use(express.json());

//我这边使用了中间件
var cors=require("cors");

app.use(cors()); 

// Home route
app.get('/', (req, res) => {
  PGutils.query('select * from topdp_user_info',null)
  res.send('Hello, World!');
});

// Sample GET route
app.get('/api/getUrl/:md5/:urlMd5', (req, res) => {
  try{
    const md5 = req.params.md5;
    const urlMd5 = req.params.urlMd5;
    pgUtils.query(`select * from click_info where click_info_md5 = '${md5}' and current_url_md5='${urlMd5}'`).then(rows =>{
      
      if(!rows){
        res.json({ success: false,message: '服务端异常' });
        return;
      }
      console.log(" next page md5 ", rows.target_url_md5);
      if(!rows.target_url_md5 ||  rows.target_url_md5 == 'null'){
        res.json({ success: false,message: '服务端异常' });
      }
      rows.success = true;
      rows.target_url_md5 = `/${rows.target_url_md5}.html`;
      res.json({ success: true,data:rows});
    })
  }catch(error){
    res.json({ success: false,message: '服务端异常' });
  }
 
});

// Sample POST route
app.post('/data', (req, res) => {
  const receivedData = req.body;
  re
  res.json({ receivedData, message: 'Data received successfully!' });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});